package cn.net.xyan.easy.webapp.base.entity.format;

import cn.net.xyan.easy.spring.jpa.utils.sequence.AbstractSequenceFormat;
import cn.net.xyan.easy.webapp.base.entity.Archive_;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by xiashenpin on 16/1/20.
 */
public class ArchiveIDFormat extends AbstractSequenceFormat {

    public static final String FormatClass = "cn.net.xyan.easy.webapp.base.entity.format.ArchiveIDFormat";

    ThreadLocal<DateFormat> tdf = new ThreadLocal<>();

    public DateFormat dateFormat(){
        DateFormat dateFormat = tdf.get();
        if (dateFormat == null){
            dateFormat = new SimpleDateFormat("yyyyMMdd");
            tdf.set(dateFormat);
        }
        return tdf.get();
    }

    @Override
    public Serializable formatSequence(Class<? extends Serializable> returnClass, Long sequence, Object[] propertyStates, String[] propertyNames, String propertyName) {
        Date now = new Date();
        String today = dateFormat().format(now);
        String fileName = findPropertyValue(propertyStates,propertyNames, Archive_.fileName);
        String stringValue = String.format("%s%s%08d",fileName,today,sequence);
        if (Long.class.isAssignableFrom(returnClass)){
            return Long.valueOf(stringValue);
        }else if(String.class.isAssignableFrom(returnClass)){
            return stringValue;
        }
        return null;
    }
}
